//  Copyright (c) 2010 Mahesh Sharma,Matt MacDonald
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.


package org.prx.prp.view;

import java.util.LinkedList;

import org.prx.prp.R;
import org.prx.prp.controller.SchedulingManager;
import org.prx.prp.controller.StreamManager;
import org.prx.prp.utility.LocationHelper;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class LocalListActivity extends ListActivity {
	protected static final int START_LOCATING = 1119;
	
	private Context mContext;
	private LinkedList<Cursor> cursors = new LinkedList<Cursor>();
	private TextView noticeText; 
	private Drawable loader;
	
	SectionedAdapter adapter = new SectionedAdapter() {
		protected View getHeaderView(String caption, int index,
				View convertView, ViewGroup parent) {
			TextView result = (TextView) convertView;
			if (convertView == null) {
				result = (TextView) getLayoutInflater().inflate(
						R.layout.section_header,null);
			}
			result.setText(caption);
			return (result);
		}
	};
	
	
	
	private Handler mHandler = new Handler(){
		
		public void handleMessage(Message m){
			switch(m.what){
			case START_LOCATING:
				noticeText.setCompoundDrawables(null, null, loader, null);
				noticeText.setText("Locating...");
				LocationHelper.getLocation(LocalListActivity.this, this);
				break;
			case LocationHelper.FOUND_LOCATION:
				noticeText.setText("Calculating Distances...");
				StreamManager.initDistanceTable((Location)m.obj, this);
				break;
			case StreamManager.DISTANCE_TABLE_CREATED:
				notifyDataSetChanged();
				noticeText.setText("");
			}
		}
	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		mHandler.sendEmptyMessage(START_LOCATING);
		addDistanceSection(0, 51, "Within 50 Miles");
		addDistanceSection(50,251,"Within 250 Miles");
		addDistanceSection(250,501,"Within 500 Miles");
		addDistanceSection(500,100000,"Beyond 500 Miles");
		setListAdapter(adapter);		
		ListView listView = getListView();
		setContentView(listView);        
		listView.setOnItemClickListener( new OnItemClickListener() {
			public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
				Cursor cursor=(Cursor) adapter.getItem(position);
		        int programIDOfSelectedItem=cursor.getInt(cursor.getColumnIndex("STREAM_ID"));
		        String displayName=cursor.getString(cursor.getColumnIndex("STREAM_DISPLAY_NAME"));
		        Bundle bundle=new Bundle();
				bundle.putInt("STREAM_ID",programIDOfSelectedItem);
				bundle.putString("STREAM_DISPLAY_NAME",displayName);
				Intent intent=new Intent(mContext,StationInformationView.class);
				intent.putExtras(bundle);
				System.out.println("Hmmm, trying for " + programIDOfSelectedItem);
				startActivity(intent);
		    }
		});
		
		
		setContentView(R.layout.main1);
		
		
		noticeText = (TextView)getParent().findViewById(R.id.top_notice);
		
		listView.setHorizontalFadingEdgeEnabled(false);
		getListView().setBackgroundColor(Color.parseColor("#FFFFFF"));
		getListView().setCacheColorHint(Color.parseColor("#FFFFFF"));
		
		loader = getResources().getDrawable(R.drawable.ajax_loader);
		
		if (loader != null) {
			System.out.println("Loaded it!");
		} else {
			System.out.println("Nope");
		}
		mContext=this;
		
	}
	private void addDistanceSection(int lowerLimit,int upperLimit,String message)
	{
		Cursor cursor=SchedulingManager.getInstance().findSchedulingsByDistance(lowerLimit,upperLimit);
		cursors.add(cursor);
		startManagingCursor(cursor);
		adapter.addSection(message,new SimpleCursorAdapter(this,R.layout.stream_info_item,cursor, new String[] {"STREAM_DISPLAY_NAME","PROGRAM_TITLE","TIME"}, // Number for child layouts
                new int[] {R.id.stream_name,R.id.program_title,R.id.schedule_time}));		
		
	}
	
	private void notifyDataSetChanged(){
		Object[] cs = cursors.toArray();
		for(int i = 0; i < cs.length; i++){
			((Cursor)cs[i]).requery();
		}
		adapter.notifyDataSetChanged();
	}

}
